<?
	require_once(dirname(__FILE__).'/../conf/conf.php');
	require_once(dirname(__FILE__).'/simple_curl.php');
	session_start();
	if (isset($_overwrite_sid))
	{
		session_id($_overwrite_sid);
		echo 'session started with $_overwrite_sid = ' . $_overwrite_sid;
	}

	function _saveGoogleTokenInfo($googleTokenInfo) {
		foreach ( $googleTokenInfo as $key => $value) {
			$_SESSION['g_' . $key] = $value;
		}
	}

	/**
		
		To call following $_SESSION variable MUST BE SET
			$_SESSION['g_access_token'] = retrieve from authentication
			$_SESSION['g_refresh_token'] = auto refresh will update this values.

		Also require GLOBAL $google_app_client ASSOC array variable MUST BE SET: 
			$google_app_client['id'] = * check your google api console *
			$google_app_client['secret'] = * check you google api console *

		Calling GoogleApi @param $_api_name supports values ...
			'info' get user information.
		
		@return return associative array of object.
		@return out_ $result - unchange upon success, FALSE upon failure.
		@return out_ $err - $err will accompany when $result is false.

	*/
	function callGoogleApi($_api_name, $_request, $result, $err, $state = 0) {
		GLOBAL $google_app_client;

		// check g_access_token before call.
		if ( ! isset($_SESSION['g_access_token'])) {
			$err = '$sil$ invalid session';
			$result = FALSE;
			return NULL;
		}

		switch ($_api_name) {
		case 'info':
			$r = cURLGet(
				'https://www.googleapis.com/oauth2/v1/userinfo', 
				array(
					'access_token' => $_SESSION['g_access_token']
				), 
				&$result, 
				&$err);
			break;
		default:
			$result = FALSE;
			$err = 'unknwon \'api_name\' value: ' . $api_name;
			return;
		}

		$r = json_decode($r, true);

		if ($result && isset($r['error']['message']) && $r['error']['message'] == 'invalid token') {

			if ($state == 1) {
				// already try refresh token
				$err = 'token invalid, unable to refresh token. Please, relogin';
				$result = FALSE;
				return NULL;
			}
			$_token = cURLPost(
				'https://accounts.google.com/o/oauth2/token',
				array(
					'client_id' => $google_app_client['id'],
					'client_secret' => $google_app_client['secret'],
					'refresh_token' => $_SESSION['g_refresh_token'],
					'grant_type' => 'refresh_token'
				), 
				&$result, 
				&$err);

			$_token = json_decode($_token, true);
			_saveGoogleTokenInfo($_token);

			// retry
			$r = callGoogleApi($_api_name, $_request, &$result, &$err, 1);
		}

		return $r;
	}
?>